package com.pai4j.search.messagequeue.consumer;

import com.pai4j.common.enums.ESMessageTypeEum;
import com.pai4j.common.enums.messagequeue.MessageQueueEnum;
import com.pai4j.common.service.messagequeue.consumer.AbstractRedisQueueConsumer;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.vo.dto.AbstractESMessageDTO;
import com.pai4j.domain.dto.queue.MomentEsSyncQueueDTO;
import com.pai4j.domain.vo.response.moment.MomentVO;
import com.pai4j.search.service.es.MomentElasticSearchService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
@Lazy(false)
public class MomentSyncRedisQueueConsumer extends AbstractRedisQueueConsumer<MomentEsSyncQueueDTO> {

    @Resource
    private MomentElasticSearchService momentElasticSearchService;

    public void initBean() {
        new Thread(() -> schedule()).start();
    }

    @Override
    protected MomentEsSyncQueueDTO convert(String s) {
        return JsonUtil.fromJson(s, MomentEsSyncQueueDTO.class);
    }

    @Override
    protected MessageQueueEnum getMessageQueue() {
        return MessageQueueEnum.QUEUE_MOMENT_SYNC_ES;
    }

    @Override
    protected void receive(MomentEsSyncQueueDTO msg) throws Exception {
        MomentVO moment = JsonUtil.fromJson(msg.getMomentJson(), MomentVO.class);
        momentElasticSearchService.sync(buildES(moment));
    }

    private AbstractESMessageDTO buildES(MomentVO m) {
        AbstractESMessageDTO dto = new AbstractESMessageDTO();
        dto.setType(ESMessageTypeEum.MOMENT.getType());
        dto.setBizId(String.valueOf(m.getId()));
        StringBuilder content = new StringBuilder();
        if (StringUtils.isNotBlank(m.getContent())) content.append(m.getContent());
        // 可选：拼接AI摘要、关键词
        dto.setContent(content.toString());
        dto.setData(JsonUtil.toJsonString(m));
        Date now = new Date();
        dto.setCreateDate(now);
        dto.setUpdateDate(now);
        return dto;
    }

    @Override
    protected void error(MomentEsSyncQueueDTO data, Exception ex) {
        backToQueue(data);
        log.error("MomentSyncRedisQueueConsumer error", ex);
    }
}
